<?php

namespace app\api\logic;

use app\common\model\CollectCourse;
use app\common\model\CollectQuestion;
use think\Exception;
use think\response\Json;

class Collect
{

    /**
     * 查询列表
     * @param $param
     * @return array
     */
    public function getList($param): array
    {
        // 提取参数
        $type = $param['type'] ?? 0;  // 0.查询收藏题目   1.查询收藏课程
        $userId = $param['userId'];
        $course_id = $param['course_id'] ?? 0;
        if ($type) {
            return $this->getCollectCourseByUserId($userId, $course_id);
        } else {
            return $this->getCollectQuestionByUserId($userId, $course_id);
        }
    }

    /**
     * 查询列表
     * @param $param
     * @return array
     */
    public function getProfession($param): array
    {
        // 提取参数
        $type = $param['type'] ?? 0;  // 0.查询收藏题目   1.查询收藏课程
        $userId = $param['userId'];

        if ($type) {
            return $this->getCollectCourseByUserId($userId);
        } else {
            return $this->getCollectQuestionByUserId($userId);
        }
    }

    /**
     * getCollectCourseByUserId
     * @param $userId
     * @return array
     */
    private function getCollectCourseByUserId($userId, $course_id)
    {
        //查询条件
        $where = [
            'a.user_id' => $userId,
            'a.status' => 1
        ];
        if ($course_id) {
            $where['a.course_id'] = $course_id;
        }
        // 查询数据
        $field = 'course_id,b.code,b.name';
        $list = app(CollectCourse::class)
            ->alias('a')
            ->field($field)
            ->leftJoin('course b', 'a.course_id = b.id')
            ->where($where)
            ->select();
        $list = $list ? $list->toArray() : [];
        return $list;
    }

    /**
     * getCollectQuestionByUserId
     * @param $userId
     * @return array
     */
    private function getCollectQuestionByUserId($userId, $course_id)
    {
        //查询条件
        $where = [
            'a.user_id' => $userId,
            'a.status' => 1
        ];
        if ($course_id) {
            $where['a.course_id'] = $course_id;
        }

        // 查询数据
        $field = 'count(*) count,a.course_id,b.code,b.name';
        $list = app(CollectQuestion::class)
            ->alias('a')
            ->leftJoin('course b', 'a.course_id = b.id')
            ->field($field)
            ->where($where)
            ->group('course_id')
            ->select();
        $list = $list ? $list->toArray() : [];
        return $list;
    }

}